import { _decorator, Component, Node } from 'cc';
import { local_bool, local_num, local_set } from '../localData/LocalData';
import { AudioSource } from 'cc';
import { AudioClip } from 'cc';
import ResLoader from '../resource/ResLoader';
const { ccclass, property } = _decorator;

@ccclass('BgmAudioSource')
export class BgmAudioSource extends Component {
    // 声音开关
    private _enableKey: string = '__sgame_bgm_enable';
    private _enable: boolean = true;
    public get enable(): boolean {
        return this._enable;
    }

    public set enable(enable: boolean) {
        this._enable = enable;
        local_set(this._enableKey, enable);
        this.checkPlay();
    }

    // 背景音乐大小
    private _volumnKey: string = '__sgame_bgm_volumn';
    private _volumn: number = 1;
    public get volumn(): number {
        return this._volumn;
    }

    public set volumn(volumn: number) {
        this._volumn = volumn;
        local_set(this._volumnKey, volumn);
        this._audioSource.volume = volumn;
        this.checkPlay();
    }

    private _audioSource: AudioSource;
    private _stopped: boolean = false;

    onLoad() {
        this._audioSource = this.node.addComponent(AudioSource);
        this._audioSource.loop = true;
        this.enable = local_bool(this._enableKey, true);
        this.volumn = local_num(this._volumnKey, 1);
    }

    public async play(bgm: AudioClip | string) {
        if (typeof bgm === 'string') {
            bgm = await ResLoader.LoadAssetSync(bgm, AudioClip);
        }

        this._audioSource.clip = bgm;
        this._stopped = false;
        this.checkPlay();
    }

    // 检测需要播放则播放
    public checkPlay() {
        if (!this._audioSource.clip) {
            return;
        }

        if (this._stopped) {
            return;
        }

        if (!this._enable) {
            this._audioSource.stop();
            return;
        }

        if (this._audioSource.playing) {
            return;
        }

        this._audioSource.play();
    }

    /**
     * 停止 bgm，通过这个函数暂停 bgm 后，必须通过 play 函数来播放 bgm，才能继续播放
     */
    public stop() {
        this._audioSource.stop();
        this._stopped = true;
    }
}
